<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Bistro;
use App\Model\BistroIncomeDay;
use App\Model\BistroIncomeMonth;
use App\Transformers\BistroTransformer;
use App\Transformers\BistroIncomeDayTransformer;
use App\Transformers\BistroIncomeMonthTransformer;


class BistroController extends Controller
{
    /**
     * 分店日统计
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function staticDay(Request $request) {
        $bistro = $request->user('bistro');
        $input = $request->all();
        $date_start = date('Y-m').'-01';
        $date_end = date('Y-m-d');
        $stimestamp = strtotime($date_start);
        $etimestamp = strtotime($date_end);
        // 计算日期段内有多少天
        $days = ($etimestamp-$stimestamp)/86400+1;

        $data = [];
        $data['data'] = [];

        // 保存每天日期
        $date = array();
        for($i=0; $i<$days; $i++){
            $date[] = date('Y-m-d', $stimestamp+(86400*$i));
        }

        foreach ($date as $ddd) {
            $bistro_income_day = BistroIncomeDay::date($ddd)->where('bistro_id', $bistro->id)->first();
            if(empty($bistro_income_day)) {
                array_push($data['data'], 0);
            }else{
                array_push($data['data'], $bistro_income_day['income'] * 1 - $bistro_income_day['outcome'] * 1);
            }
        }

        $data['type'] = 'line';
        $data['smooth'] = true;

        $return_data = [
            'days' => $date,
            'data' => [$data]
        ];
        return $this->apiSuccess($return_data);
//        dd($data);

//        $bistro_income_days = BistroIncomeDay::date($input['date'])->paginate(10);
//        $data['data'] = [
//            'bistro_income_days' => $this->factalPaginator($bistro_income_days, new BistroIncomeDayTransformer())
//        ];
//        return $this->apiSuccess($data);
    }

    /**
     * 分店月统计
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function staticMonth(Request $request) {
        $bistro = $request->user('bistro');

        $year = date('Y');
        $month = (int)date('m');
        $months = [];
        for ($i = 1; $i <= $month; $i++){
            if($i <= 9) {
                array_push($months, $year.'-0'.$i);
            }else{
                array_push($months, $year.'-'.$i);
            }
        }
        $data = [];
        $data['data'] = [];
        $data['type'] = 'line';
        $data['smooth'] = 'true';

        foreach ($months as $mn) {
            $bim = BistroIncomeMonth::where('bistro_id', $bistro->id)->where('month', $mn)->first();
            if(empty($bim)) {
                array_push($data['data'], 0);
            }else{
                array_push($data['data'], $bim['income'] * 1 - $bim['outcome'] * 1);
            }
        }

        $return_data = [
            'months' => $months,
            'data' => $data
        ];

        return $this->apiSuccess($return_data);
//        BistroIncomeMonth

//        $input = $request->all();
//        $bistro_income_months = BistroIncomeMonth::month($input['month'])->paginate(10);
//        $data['data'] = [
//            'bistro_income_months' => $this->factalPaginator($bistro_income_months, new BistroIncomeMonthTransformer())
//        ];
//        return $this->apiSuccess($data);
    }

    /**
     * 分店列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request) {
       $head_store = $request->user('api');
       $bistros = Bistro::where('head_store_id', $head_store->id)->paginate(10);
       $data['data'] = [
           'bistros' => $this->factalPaginator($bistros, BistroTransformer::forBackendStatis())
       ];
       return $this->apiSuccess($data);
    }

    /**
     * 分店详情 带月统计
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request, $id) {
        $head_store = $request->user('api');
        $bistro = Bistro::headStoreId($head_store->id)->where('id', $id)->first();
        if(empty($bistro)) return $this->apiError('找不到相关店铺');
        //统计本月
        $this_month = date('Y-m');
        $bistro_income_month = BistroIncomeMonth::bistroId($bistro->id)->month($this_month)->first();
        if(empty($bistro_income_month)) {
            $Bistro_month = [
                'month' => $this_month,
                'year' => date('Y'),
                'income' => '0.00',
                'outcome' => '0.00'
            ];
        }else{
            $Bistro_month = $this->fractalItem($bistro_income_month, new BistroIncomeMonthTransformer());
        }
        $data['data'] = [
            'bistro' => $this->fractalItem($bistro, new BistroTransformer()),
            'bistro_income_month' => $Bistro_month
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 店铺的日统计
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function staticBistro(Request $request, $id) {
        $head_store = $request->user('api');
        $bistro = Bistro::headStoreId($head_store->id)->where('id', $id)->first();
        if(empty($bistro)) return $this->apiError('找不到相关店铺');

        //本月30天的情况
        $this_date_start = date('Y-m').'-01';
        $this_date_end = date('Y-m-d');
        $bistro_income_days = BistroIncomeDay::bistroId($bistro->id)->dateFrom($this_date_start, $this_date_end)->paginate(20);

        $data['data'] = [
            'bistro_income_days' => $this->factalPaginator($bistro_income_days, new BistroIncomeDayTransformer())
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 创建店铺
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(Request $request) {
        $head_store = $request->user('api');
        $input = $request->all();
        //验证
        $validateResult = $this->validateCreateBistro($input);
        if ($validateResult["errorCode"] > 0) return $this->apiError($validateResult["message"], $validateResult["errorCode"]);
        $bistro = $this->_setBistro(new Bistro(), $input);
        $bistro->head_store_id = $head_store->id;
        $bistro->save();
        $data['data'] = [
            'bistro' => $this->fractalItem($bistro, new BistroTransformer())
        ];
        return $this->apiSuccess($data);
    }

    private function _setBistro($bistro, $input) {
        $bistro->name = $input['name'];
        $bistro->qr_code = $input['qr_code'];
        $bistro->start_fee = $input['start_fee'];
        $bistro->area = $input['area'];
        $bistro->address = $input['address'];
        $bistro->account = $input['account'];
        $bistro->password =  bcrypt($input['password']);
        return $bistro;
    }


    public function update() {

    }

    public function delete() {

    }

    private function validateCreateBistro($input) {
        $name = isset($input['name']) ? $input['name']: '';
        $qr_code = isset($input['qr_code']) ? $input['qr_code']: '';
        $start_fee = isset($input['start_fee']) ? $input['start_fee']: '';
        $area = isset($input['area']) ? $input['area']: '';
        $address = isset($input['address']) ? $input['address']: '';
        $account = isset($input['account']) ? $input['account']: '';
        $password = isset($input['password']) ? $input['password']: '';


        if(empty($name)){
            return [
                "message" => "点名不得为空",
                "errorCode" => 5000
            ];
        }

        if(empty($qr_code)){
            return [
                "message" => "二维码不得为空",
                "errorCode" => 5000
            ];
        }

        if(empty($start_fee)){
            return [
                "message" => "起送费不得为空",
                "errorCode" => 5000
            ];
        }

        if(empty($area)){
            return [
                "message" => "地区不得为空",
                "errorCode" => 5000
            ];
        }

        if(empty($address)){
            return [
                "message" => "详细地址不得为空",
                "errorCode" => 5000
            ];
        }

        if(empty($account)){
            return [
                "message" => "账户不得为空",
                "errorCode" => 5000
            ];
        }

        if(empty($password) || strlen($password) > 40 || strlen($password) < 5 ){
            return [
                "message" => "密码不得为空或密码小于5位或大于40位",
                "errorCode" => 5000
            ];
        }

        return [
            "message" => "没有错误信息",
            "errorCode" => 0
        ];

    }
}
